require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UIArenaMain = {};
HelperFunc.SetUIEnv(UIArenaMain)
local this = UIArenaMain;

-- this.gameObject = nil;
this.transform = nil;
this.LuaBehaviour = nil;

this.hasInit = false;
--this.rewards = {};
--this.txtLevelName = nil;
--this.txtScore = nil;
--this.txtRank = nil
----------------------------------------utimer----------------------------------------
this.idleTimer = nil;--升段位特效回调 utimer
this.timeRefresh = nil;--刷新时间计时器
----------------------------------------btn-----------------------------------------------------
this.btnExplainBtn = nil;--段位预览按钮
this.btnRefresh = nil;--对手刷新按钮
this.btnFormation = nil;--防守阵容按钮
this.btnTickAdd = nil;--点击购买门票按钮
this.btnJump = nil;--查看门票获取途径按钮
this.btnBack = nil;--返回按钮
this.btnRank = nil;--查看排行榜
this.btnWonderful = nil;--查看精彩战斗


----------------------------------------text-----------------------------------------------------
this.txtCountDownTime = nil;--赛季时间文本
this.txtTickCount = nil;--当前门票数量
--this.txtDayTime = nil;--每日结算时间文本
--this.txtSeasonTime = nil;
----------------------------------------spineAnimation-----------------------------------------------------
this.imgLevel = nil;--新段位动画
----------------------------------------list-----------------------------------------------------
--this.objDayContent = nil;--每日结算奖励
--this.objSeasonContent = nil;
----------------------------------------data-----------------------------------------------------
this.refreshTimeNum = 0;--刷新敌人cd时间
----------------------------------------loader------------------------------------------------
this.imgTickIcon = nil;


--this.objBoxContent = nil;
--this.objOpponentContent = nil;
this.btnRecord = nil;
this.btnReward = nil;
this.showCtrl = nil;
this.typeCtrl = nil;
this.numMyRankText = nil;
this.numMyPointText = nil;
this.numDefendPowerText = nil;
this.rewardBoxs = {};
this.rewardProgressBar = nil;
this.numRewardBarText = nil;
this.levelImgIcon = nil;
this.textRankText = nil;
this.levelUpPage = nil;
this.mainReward = nil;
this.seasonRewards = {};
this.oppoList = {};
this.dayRewards = {}

-- this.arenaBoxConfig = nil;
this.upAni = nil;
this.timer = nil;
-- this.arenaBaseInfo = nil;
this.btntip = nil;

this.ifShowRewardController = nil;
this.showReward = nil;
this.btnShowRewardClose = nil;
this.showRewardList = nil;
this.playerItems = {};
this.rankShowItems = {};
this.arenaTips = nil;

local ArenaType2FuncIdMap =
{
   [EnumConst.ArenaBattleType.Normal] = 301,
   [EnumConst.ArenaBattleType.Cross] = 308,
   [EnumConst.ArenaBattleType.TeamCross] = 309,
}

function UIArenaMain.Init( _arena_type )
    this.cur_arena_type = tonumber(_arena_type) or EnumConst.ArenaBattleType.Normal

    --todo 应该小写 暂时先大写
    -- if arenaBoxConfig == nil then
    --     arenaBoxConfig = G.dataTable["t_arenaboxreward"];
    -- end
    
    if this.timer == nil then
        this.timer = Timer.New(this.countDown, 1, 9999999,true)
    end
    
    
    local name, packageName = getUIName(PanelResNames.UIArenaMain);
    panelMgr:Push(name, packageName, this.onCreate, Config.useLocalUI);
end

function UIArenaMain.onCreate(obj)
    AddUIPackageDepend(PanelResNames.UIArenaMain, "FUI/SmallBodyAtlas")
    if not hasInit then
        -- gameObject = obj;
        hasInit = true;

        -- title
        local n110 = obj:GetChild("n110")
        local txt_title = n110:GetChild("title")
        if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
            txt_title.text = getLanguage("FunctionName301")
        elseif  this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
            txt_title.text = getLanguage("FunctionName308")
        elseif  this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
            txt_title.text = getLanguage("FunctionName309") -- "多队跨服竞技场" --
        else
            error("错误竞技场类型")
        end

        mainReward = obj:GetChild("mainReward")

        ----loader----
        imgTickIcon = obj:GetChild("imgTickIcon")
        ----text----
        txtCountDownTime = obj:GetChild("TimeText")
        txtTickCount = obj:GetChild("txtTickCount")
        ----spineAnimation-----
        imgLevel = obj:GetChild("Effect_Dwsg") 
        local skelton_data = imgLevel.displayObject.cachedTransform:Find("GoWrapper/effect_dwsg_SkeletonData")
        if skelton_data ~= nil then
            local anim = skelton_data:GetComponent("SkeletonAnimation")
            local effect_mat = Util.GetMaterialOnSkeletonAnimation(anim, "effect_dwsg_Material")
            if effect_mat then
                effect_mat:SetFloat("_StencilComp", 8)
            end
            local effect_mat2 = Util.GetMaterialOnSkeletonAnimation(anim, "effect_dwsg_Material-Additive")
            if effect_mat2 then
                effect_mat2:SetFloat("_StencilComp", 8)
            end
        end
        ----btn----
        btnRefresh = obj:GetChild("RefreshBtn")
        btnExplainBtn = obj:GetChild("ExplainBtn")
        btnFormation = obj:GetChild("FormationBtn")
        btnTickAdd = obj:GetChild("btnTickAdd")
        btnJump = obj:GetChild("btnJump")
        btnBack = obj:GetChild("BackBtn")
        btnRank = obj:GetChild("RankBtn")

        --txtDayTime = obj:GetChild("DayTimeText")
        --objDayContent = obj:GetChild("DayRewardList")
        --txtSeasonTime = obj:GetChild("SeasonTimeText")
        --objSeasonContent = obj:GetChild("SeasonRewardList")
        --objOpponentContent = obj:GetChild("OpponentList")
        btnWonderful = obj:GetChild("WonderfulBtn")
        btnRecord = obj:GetChild("RecordBtn")
        btnReward = obj:GetChild("btnReward")
        showCtrl = obj:GetController("showCtrl");
        typeCtrl = obj:GetController("typeCtrl");
        btntip = obj:GetChild("n20");
        numMyRankText = obj:GetChild("numMyRank");
        numMyPointText = obj:GetChild("numMyPoint");
        numDefendPowerText = obj:GetChild("numDefendPower");
        numRewardBarText = obj:GetChild("numRewardBar");
        rewardProgressBar = obj:GetChild("rewardProgressBar");
        levelImgIcon = obj:GetChild("LevelImg");
        textRankText = obj:GetChild("textRank");
        numHighPowerText = obj:GetChild("numHighPower");
        levelUpPage = obj:GetChild("n216");
        levelUpController = obj:GetController("LevelUp");
        ifShowRewardController = obj:GetController("ifShowReward");
        showReward = obj:GetChild("n217");
        btnShowRewardClose = showReward:GetChild("btnCloseReward");
        showRewardList = showReward:GetChild("itemGrid");
        upAni = levelUpPage:GetChild("Effect_Dwjs");
        arenaTips = obj:GetChild("tips");
        this.sourceUIobj = obj:GetChild("UISourceMultiple");
        this.showSourceController = obj:GetController("showSource")
        rewardBoxs = {};
        playerItems = {};
        rankShowItems = {};
        for i = 1, 5 do
            local boxItem = obj:GetChild("reward" .. i);
            table.insert(rewardBoxs, boxItem)
        end
        for i = 1, 5 do
            local playerItem = obj:GetChild("player" .. i);
            table.insert(playerItems, playerItem);
        end
        for i = 1, 3 do
            local rankItem = obj:GetChild("rank" .. i);
            table.insert(rankShowItems, rankItem);
        end

        ---------------------------------------------
        -- 跨服竞技场
        ---------------------------------------------
        this.cross_server_controller = obj:GetController("ifCrossService")
        if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
            this.cross_server_controller:SetSelectedIndex(0)
        elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
            this.cross_server_controller:SetSelectedIndex(1)
        elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
            this.cross_server_controller:SetSelectedIndex(2)
        else
            error("错误竞技场玩法类型")
            return
        end
        this.refreshMainReward()

        this.opponent_list = obj:GetChild("OpponentList") 
        this.opponent_list.itemRenderer = this.renderOpponentListItem
        this.opponent_list2 = obj:GetChild("OpponentList2") 
        this.opponent_list2.itemRenderer = this.renderOpponentListItem
        -- this.opponent_list:SetVirtual()
        ----------------------------------------------
        -- end
        ----------------------------------------------

        ---------------------------------------------
        -- 跨服多对竞技场
        ---------------------------------------------
        this.teamCrossFirstCtrl = obj:GetController("first");
        this.teamCrossArenaTips1 = obj:GetChild("tips2");
        this.teamCrossArenaTips2 = obj:GetChild("tips3");
        this.comp_box = obj:GetChild("box") 
        this.ctrl_box_state = this.comp_box:GetController("state")
        this.txt_produce = this.comp_box:GetChild("produce")
        this.txt_storage = this.comp_box:GetChild("storage")
        this.img_icon = this.comp_box:GetChild("icon")
        this.btn_shop = obj:GetChild("btnShop")
        this.txt_box_tips = this.comp_box:GetChild("tips")
        this.txt_box_tips.text = "挑战任意对手即可获取高阶竞技场收益"--getLanguage("")
        local box_effect = this.comp_box:GetChild("effect_jjcbx")
        if box_effect ~= nil then
            local box_effect_obj = box_effect.displayObject.cachedTransform:Find("GoWrapper/effect_jjcbx_SkeletonData")
            if box_effect_obj ~= nil then
                this.box_effect_ani  = box_effect_obj:GetComponent("SkeletonAnimation")
                if this.box_effect_ani ~= nil then
                    Util.PlayAction(this.box_effect_ani, "idle", true)
                end
            end
        end
        ----------------------------------------------
        -- end
        ----------------------------------------------
        this.addEvent();
    end
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        arenaHandler.sendReqArenaInfo()
        logicMgr.ArenaManager.requestRankInfo()
        logicMgr.ArenaManager.requestOpponentInfo(true) --- 创建时请求一次对战列表
        this.refresh();
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        this.opponent_data_list = {}
        this.opponent_list.numItems = 0
        crossArenaHandler.sendReqCrossArenaInfo()
        logicMgr.ArenaManager.requestCrossRankInfo()
        logicMgr.ArenaManager.requestCrossOpponentInfo(true)
    elseif  this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        this.opponent_data_list = {}
        this.opponent_list2.numItems = 0
        crossTeamArenaHandler.sendReqHighArenaInfo()
        logicMgr.ArenaManager.requestCrossTeamRankInfo()
        logicMgr.ArenaManager.requestCrossTeamOpponentInfo(true)
        if FightManager.cross_team_battle_record ~= nil then
            this.onClickRecord()
            showUI(PanelNames.UIRecord, FightManager.cross_team_battle_record )
            FightManager.cross_team_battle_record = nil
        end
        this.teamCrossArenaTips1 = getLanguage("ArenaHLTips6");
        this.teamCrossArenaTips2 = getLanguage("ArenaHLTips7");
    else
        error("错误竞技场玩法类型")
        return
    end

end

function UIArenaMain.addEvent()

    btnExplainBtn.onClick:Add(this.onClickExplain)
    btnRefresh.onClick:Add(this.onClickRefresh)
    btnFormation.onClick:Add(this.onClickFormation)
    btnTickAdd.onClick:Add(this.onClickTickAdd)
    this.btnJump.onClick:Add(this.onClickSource)
    btnBack.onClick:Add(this.onClickClose)
    btnRank.onClick:Add(this.onClickRank)
    btnWonderful.onClick:Add(this.onClickWonderful)
    btnRecord.onClick:Add(this.onClickRecord)
    btnReward.onClick:Add(this.onClickReward)
    btntip.onClick:Add(this.ShowTips)

    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        UIRedDots.addViewListen(PanelNames.UIArenaMain, "btnFormation", this.btnFormation, Config.RedDotsType.defFormation,EnumConst.FormationType.ArenaDef)--防守阵容红点
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        UIRedDots.addViewListen(PanelNames.UIArenaMain, "btnFormation", this.btnFormation, Config.RedDotsType.defFormation, EnumConst.FormationType.CrossArenaDef)--跨服防守阵容红点
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        -- UIRedDots.addViewListen(PanelNames.UIArenaMain, "btnFormation", this.btnFormation, Config.RedDotsType.defFormation, EnumConst.FormationType.TeamCrossArenaDef)--多队跨服防守阵容红点
        UIRedDots.addViewListen(PanelNames.UIArenaMain, "btnRewardPreview", this.btnReward, Config.RedDotsType.CrossTeamRewardPreview)--多队跨服奖励预览红点
        this.comp_box.onClick:Add(this.onClickOfflineReward)
        this.btn_shop.onClick:Add(this.onClickArenaShop)
    else
        error("错误竞技场玩法类型")
        return
    end
    btnShowRewardClose.onClick:Add(function()
        ifShowRewardController.selectedIndex = 0;
    end)
end

function UIArenaMain.onClickOfflineReward()
    if this.last_click_offline_reward ~= nil and UnityEngineTime.realtimeSinceStartup - this.last_click_offline_reward < 1 then
        return
    end
    local baseInfo = logicMgr.ArenaManager.getCrossTeamBaseInfo() 
    this.last_click_offline_reward = UnityEngineTime.realtimeSinceStartup
 
    if baseInfo and baseInfo.rank < 131 then
        if baseInfo.award > 0 then
            crossTeamArenaHandler.sendReqHighArenaGetAward()
            if this.box_effect_ani ~= nil then 
                Util.PlayAction(this.box_effect_ani, "idle3", true) 
            end
        else
            UISysTips.AddMsg( string.format("没有可领取的%s", ItemManager.GetItemName(31)) )
        end
    end
end

function UIArenaMain.onClickArenaShop()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.ArenaShop, true, this.btn_shop) then
        logicMgr.UIShowManager.ShowUIShop(EnumConst.ShopType.arenaShop,nil,4)  -- 竞技场商店
    end
end

function UIArenaMain.removeEvent()
    levelUpPage:GetChild("n12").onClick:Clear()
    btnExplainBtn.onClick:Clear()
    btnRefresh.onClick:Clear()
    btnFormation.onClick:Clear()
    btnTickAdd.onClick:Clear()
    this.btnJump.onClick:Clear()
    btnBack.onClick:Clear()
    btnRank.onClick:Clear()
    btnWonderful.onClick:Clear()
    btnRecord.onClick:Clear()
    btnReward.onClick:Clear()
    btntip.onClick:Clear()
    btnShowRewardClose.onClick:Clear()
    this.btn_shop.onClick:Clear()
    this.comp_box.onClick:Clear()
    UIRedDots.removeViewEvent(PanelNames.UIArenaMain)
end

function UIArenaMain.LocalListenEvent()
    
    ListenEvent(Config.EventType.Fresh_Bag,this.updateSource)
    ListenEvent(Config.EventType.Fresh_BagUseItemBack, logicMgr.ItemManager.showGetItem)
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        ListenEvent(Config.EventType.Fresh_Arena, this.refresh)
        ListenEvent(Config.EventType.Fresh_ArenaTicket, this.refreshTicket)
        ListenEvent(Config.EventType.Fresh_ArenaFormation, this.defFormationSaveSuccess)
        ListenEvent(Config.EventType.Fresh_ArenaRanks, this.refreshTopRankShow)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        ListenEvent(Config.EventType.Fresh_Cross_Arena, this.refreshCross)
        ListenEvent(Config.EventType.Fresh_CrossArenaTicket, this.refreshCrossTicket)
        ListenEvent(Config.EventType.Fresh_CrossArenaFormation, this.defFormationCrossSaveSuccess)
        ListenEvent(Config.EventType.Fresh_CrossArenaRanks, this.refreshTopRankShow)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then -- 多队跨服竞技场
        ListenEvent(Config.EventType.Fresh_Cross_Team_Arena, this.refreshCrossTeam)
        ListenEvent(Config.EventType.Fresh_CrossTeamArenaTicket, this.refreshCrossTeamTicket)
        ListenEvent(Config.EventType.Fresh_CrossTeamArenaFormation, this.defFormationCrossTeamSaveSuccess)
        ListenEvent(Config.EventType.Fresh_CrossTeamArenaRanks, this.refreshTopRankShow)
        ListenEvent(Config.EventType.Fresh_CrossTeamArenaAward, this.refreshCrossTeamArenaAward)
    else
        error("错误竞技场玩法类型")
        return
    end 
end

function UIArenaMain.LocalCloseEvent()
    
    CloseEvent(Config.EventType.Fresh_Bag, this.updateSource)
    CloseEvent(Config.EventType.Fresh_BagUseItemBack, logicMgr.ItemManager.showGetItem)
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        CloseEvent(Config.EventType.Fresh_Arena, this.refresh)
        CloseEvent(Config.EventType.Fresh_ArenaTicket, this.refreshTicket)
        CloseEvent(Config.EventType.Fresh_ArenaFormation, this.defFormationSaveSuccess)
        CloseEvent(Config.EventType.Fresh_ArenaRanks, this.refreshTopRankShow)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        CloseEvent(Config.EventType.Fresh_Cross_Arena, this.refreshCross)
        CloseEvent(Config.EventType.Fresh_CrossArenaTicket, this.refreshCrossTicket)
        CloseEvent(Config.EventType.Fresh_CrossArenaFormation, this.defFormationCrossSaveSuccess)
        CloseEvent(Config.EventType.Fresh_CrossArenaRanks, this.refreshTopRankShow)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        CloseEvent(Config.EventType.Fresh_Cross_Team_Arena, this.refreshCrossTeam)
        CloseEvent(Config.EventType.Fresh_CrossTeamArenaTicket, this.refreshCrossTeamTicket)
        CloseEvent(Config.EventType.Fresh_CrossTeamArenaFormation, this.defFormationCrossTeamSaveSuccess)
        CloseEvent(Config.EventType.Fresh_CrossTeamArenaRanks, this.refreshTopRankShow)
        CloseEvent(Config.EventType.Fresh_CrossTeamArenaAward, this.refreshCrossTeamArenaAward)
    else
        error("错误竞技场玩法类型")
        return
    end

    timer:Stop()
end

function UIArenaMain.OnDestroy()
    this.LocalCloseEvent()
    hasInit = nil;
    this.cur_show_time_str = nil
    this.removeEvent();
    --FightManager.SetRePlay(false)
    if this.opponent_list then
        this.opponent_list:Dispose()
        this.opponent_list = nil
    end
    if this.opponent_list2 then
        this.opponent_list2:Dispose()
        this.opponent_list2 = nil
    end
    this.txt_produce = nil
    this.txt_storage = nil
    this.img_icon = nil
    this.comp_box = nil

    if UIPackage.GetById("FUI/SmallBodyAtlas") then
        UIPackage.RemovePackage("FUI/SmallBodyAtlas")
    end
end

function UIArenaMain.OnEnable()
    this.LocalListenEvent();
    this.needShowHeadMenu = nil;
    --if isOpenUI(PanelNames.UIHeadMenu) then
    --    this.needShowHeadMenu = true;
    --    closeUI(PanelNames.UIHeadMenu);
    --end
end

function UIArenaMain.OnDisable()
    this.LocalCloseEvent();
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.UIArenaOpponentItem)
    --ctrlItem.CacheHeros()
    ctrlItem.onClear()
    ctrlItem.Destroy()
    --logicMgr.PetManager.setBattleShowPetInfo();
end

function UIArenaMain.ShowTips()
    local txts = {}
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        txts["title"] = "HelpTitle1"
        txts["des"] = "HelpDes1"
        txts["story"] = "FunctionStory301"
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        txts["title"] = "HelpTitle101"
        txts["des"] = "HelpDes101"
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        txts["title"] = "HelpTitle102"
        txts["des"] = "HelpDes102"
        txts["story"] = "FunctionStory301"
    else
        error("错误竞技场玩法类型")
        return
    end
    showUI(PanelNames.CommonTips, txts);
end

function UIArenaMain.delayIdle()
    levelUpController.selectedIndex = 1;
    if upAni ~= nil then
        upAni.spineAnimation.state:SetAnimation(0, "idle2", true);
    end

end
-- 刷新排行
function UIArenaMain.refreshTopRankShow()
    local rankCfg = nil
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        rankCfg = logicMgr.ArenaManager.getRankInfo().ranks
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        rankCfg = logicMgr.ArenaManager.getCrossRankInfo().ranks
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        rankCfg = logicMgr.ArenaManager.getCrossTeamRankInfo().ranks
    else
        error("错误竞技场玩法类型")
        return
    end
    -- print("------------------->rankCfg:", table.tostring(rankCfg) )
    for i = 1, #rankShowItems do
        local data = rankCfg[i]
        if data ~= nil then
            local item = rankShowItems[i];
            local head = item:GetChild("head"):GetChild("head"):GetChild("HeadIcon");
            local frame = item:GetChild("head"):GetChild("frame");
            local name = item:GetChild("name");
            --head.url =logicMgr.SkinManager.GetHeroIconBySkinId(data.headId)
            --frame.url = "ui://ICONAtlas/" .. data.headFrame;
            UIComponentInterface:SetPlayerIcon(head, data.headId, frame, data.headFrame);
            local server_name_controller = item:GetController("ServerName")
            if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
                name.text = data.name
                server_name_controller:SetSelectedIndex(0)
            elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross 
                or this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
                if AppConst.ServerId ~= data.serverId  then
                    name.text = string.format("[%s]%s", data.serverId, data.name)
                else
                    name.text = data.name
                end
                server_name_controller:SetSelectedIndex(1)
                local txt_server_name = item:GetChild("textSevers")
                local sever_data = logicMgr.LoginManager.GetServerInAll(data.serverId)
                if sever_data ~= nil then
                    txt_server_name.text = sever_data[Server_ENU_INDEX.NAME] 
                else
                    txt_server_name.text = "未知"
                end
            else
                error("错误竞技场玩法类型")
                return
            end
        else
            local item = rankShowItems[i]
            if item ~= nil then
                local name = item:GetChild("name")
                name.text = getLanguage("BillboardRankNeedPlayer")
                local server_name_controller = item:GetController("ServerName")
                server_name_controller:SetSelectedIndex(0)
            end
        end
    end
end

function UIArenaMain.refresh()
    local rewardCfg = G.dataTable["t_arenaboxreward"] 
    local baseInfo = logicMgr.ArenaManager.getBaseInfo()
    if baseInfo == nil then return end
    if baseInfo.add == nil then baseInfo.add = 0 end
    local gradingCfg, newLevel = logicMgr.ArenaManager.getLevelConfigByScore(baseInfo.score, EnumConst.ArenaBattleType.Normal)
    
    if baseInfo.isLevelUp == 1 then
        baseInfo.isLevelUp = 0
        --播放等级修改动画
        levelUpController.selectedIndex = 1
        upAni.skinName = newLevel
        --upAni.spineAnimation.state.Data.SkeletonData:FindAnimation("idle2").Duration
        local upAniState = upAni.spineAnimation.state
        upAniState:SetAnimation(0, "idle1", false)
        local idleAniTime = upAniState.Data.SkeletonData:FindAnimation("idle1").Duration
        if idleTimer == nil then
            idleTimer = Timer.New(this.delayIdle, idleAniTime, 1, false)
        else
            idleTimer:Reset(this.delayIdle, idleAniTime, 1, false)
        end
        idleTimer:Start()
        levelUpPage:GetChild("n12").onClick:Add(function()

            if idleTimer ~= nil then
                idleTimer:Stop();
            end
            levelUpController.selectedIndex = 0
            levelUpPage.onClick:Clear()
        end)
    end
    textRankText.text = getLanguage(gradingCfg.f_Name)
    imgLevel.animationName = "idle" .. newLevel
    imgLevel.skinName = newLevel
    imgLevel.loop = true

    numMyRankText.text = baseInfo["rank"] > 0 and string.format(getLanguage("ArenaTips4"), baseInfo["rank"])or getLanguage("NotInRank");
    numMyPointText.text = baseInfo["score"]
    numDefendPowerText.text = this.getPower(EnumConst.FormationType.ArenaDef)
    numHighPowerText.text = this.getPower(EnumConst.FormationType.ArenaAtk)
    local maxKillCount = rewardCfg["5"].f_winCount
    numRewardBarText.text = baseInfo["winCount"] .. "/" .. maxKillCount
    rewardProgressBar.value = (baseInfo["winCount"] / maxKillCount) * 100
    for i = 1, #rewardBoxs do
        local item = rewardBoxs[i]
        local index = tostring(i)
        local cfg = rewardCfg[index]
        local rewardsCfg = decodeJsonStrToTabel(G.dataTable["t_arenaboxreward"][tostring(cfg.f_Id)].f_rewards);
        local itemObj = item:GetChild("item")
        local stateController = item:GetController("state")
        logicMgr.CostManager.RefreshItem(itemObj, rewardsCfg[1])
        if baseInfo["winCount"] >= cfg.f_winCount then
            if this.checkRewardId(cfg.f_Id) then
                stateController.selectedIndex = 2
            else
                stateController.selectedIndex = 1
                item.onClick:Clear()
                itemObj.onClick:Clear()
                item.onClick:Add(function()
                    this.boxRewardGet(cfg.f_Id)
                end)
                item.touchable = true
            end
        else
            stateController.selectedIndex = 0
        end
    end

    this.refreshWithData(logicMgr.ArenaManager.getOpponentInfo())
end

function UIArenaMain.refreshMainReward()
    if this.mainReward then
        local fId = ArenaType2FuncIdMap[this.cur_arena_type]
        logicMgr.FuncOpenManager.refreshMainReward(this.mainReward,fId)
    end
end
 
function UIArenaMain.refreshWithData(opponentList)
    --刷新函数
    local arenaBaseInfo = logicMgr.ArenaManager.getBaseInfo()
    this.countDown()
    timer:Stop()
    timer:Reset(this.countDown, 1, -1)
    timer:Start()

    local singleRewardConfig = logicMgr.ArenaManager.getRewardConfigByRank(arenaBaseInfo.rank)
    local singleGradConfig = logicMgr.ArenaManager.getGradCofigByScore(arenaBaseInfo.score) --段位配置
 
    this.refreshTicket();
    this.refreshOpponent(opponentList);
end

function UIArenaMain.setData(index, obj)
    local itemCtr = CtrlManager.GetCtrl(PanelNames.Item);
    local singleItemConfig = logicMgr.ItemManager.getItemConstDatabyModelId(dayRewards[index + 1][1]);
    if singleItemConfig ~= nil and itemCtr ~= nil then
        local data = {};
        data["icon"] = singleItemConfig["icon"];
        data["num"] = dayRewards[index + 1][2];
        data["quality"] = singleItemConfig["quality"];
        data["itemModelId"] = singleItemConfig.itemModelId
        itemCtr.initData(obj, data);
    end
end

function UIArenaMain.seasonSetData(index, obj)
    local itemCtr = CtrlManager.GetCtrl(PanelNames.Item);
    local singleItemConfig = logicMgr.ItemManager.getItemConstDatabyModelId(seasonRewards[index + 1][1]);
    if singleItemConfig ~= nil and itemCtr ~= nil then
        local data = {};
        data["itemModelId"] = singleItemConfig.itemModelId;
        data["icon"] = singleItemConfig["icon"];
        data["num"] = seasonRewards[index + 1][2];
        data["itemModelId"] = singleItemConfig.itemModelId
        data["quality"] = singleItemConfig["quality"];
        itemCtr.initData(obj, data);
    end
end

function UIArenaMain.refreshOpponent(opponentList)
    --对手刷新
    oppoList = {};
    oppoList = opponentList;
    for i = 1, #playerItems do
        local obj = playerItems[i];
        if i <= #oppoList then
            obj.visible = true;
            this.oppoSetData(i, obj)
        else
            obj.visible = false;
        end
    end
    local arenaBaseInfo = logicMgr.ArenaManager.getBaseInfo()
    local lastNum = (arenaBaseInfo.freeTimes + logicMgr.EcoBuffManager.getEcoBuffByTypeAndItemId(Config.EcoBuffCondition.ArenaFreeTimes)) - arenaBaseInfo.times;
    if lastNum > 0 then
        arenaTips.text = string.format(getLanguage("ArenaTips1"), lastNum);
    else
        arenaTips.text = getLanguage("ArenaTips2")
    end
end

function UIArenaMain.oppoSetData(index, obj)
    local itemCtr = CtrlManager.GetCtrl(PanelNames.UIArenaOpponentItem);
    local singleItemConfig = logicMgr.ItemManager.getItemConstDatabyModelId(CurrencyEnum.ChallengeTicket);
    local arenaBaseInfo = logicMgr.ArenaManager.getBaseInfo()
    if itemCtr ~= nil then
        local data = {};
        local controller = obj:GetController("freeCtrl");

        data.score = oppoList[index].score;
        data.rank = oppoList[index].rank;
        data.power = oppoList[index].power;
        data.playerName = oppoList[index].name;
        data.leaderId = oppoList[index].formation[1].partnerModelId;
        data.otherPetInfo = oppoList[index].otherPetInfo;
        data.costItemIconName = singleItemConfig["icon"];
        data.skill = oppoList[index].skillId;
        data.pic = oppoList[index].head
        data.isFree = arenaBaseInfo.times < (arenaBaseInfo.freeTimes + logicMgr.EcoBuffManager.getEcoBuffByTypeAndItemId(Config.EcoBuffCondition.ArenaFreeTimes));
        itemCtr.initData(obj, data, index);
        local btnBattle = obj:GetChild("BattleBtn");
        btnBattle.onClick:Clear();
        btnBattle.onClick:Add(function()
            this.OnClickOpponentItem(oppoList[index]);
        end);
        --[[        LuaBehaviour:RemoveClick(btnBattle);
                LuaBehaviour:AddClick(btnBattle,this.OnClickOpponentItem,oppoList[index + 1]);]]
    end
end

function UIArenaMain.refreshTicket()
    local tickNum = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.ChallengeTicket);
    local singleItemConfig = logicMgr.ItemManager.getItemConstDatabyModelId(CurrencyEnum.ChallengeTicket);
    imgTickIcon.url = "ui://ItemAtlas/" .. singleItemConfig["icon"];
    txtTickCount.text = tostring(tickNum);
end

function UIArenaMain.countDown()
    local arenaBaseInfo = nil
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        arenaBaseInfo = logicMgr.ArenaManager.getBaseInfo()
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        arenaBaseInfo = logicMgr.ArenaManager.getCrossBaseInfo()
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        arenaBaseInfo = logicMgr.ArenaManager.getCrossTeamBaseInfo()
    else
        error("错误竞技场玩法类型")
        return
    end

    if arenaBaseInfo ~= nil then
        local time = (arenaBaseInfo.endTime - Config.serverTime) / 1000;
        local seasonEndTime = (arenaBaseInfo.seasonEndTime - Config.serverTime) /1000;
        local timeStr = getTimeDayOrHMSStr(Mathf.Floor(time))
        local show_time_str = nil
        if seasonEndTime >time then
            --准备阶段
            show_time_str = string.format("新赛季%s后开启", timeStr)
        else
            -- txtCountDownTime.text = string.format("距离赛季结束还剩%s", timeStr); 
            show_time_str = string.format(getLanguage("ArenaTips8"), timeStr)
        end
        if this.cur_show_time_str == nil or this.cur_show_time_str ~= show_time_str then
            this.cur_show_time_str = show_time_str
            txtCountDownTime.text = show_time_str
        end
        if time <= 0 then
            if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
                arenaHandler.sendReqArenaInfo()
            elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
                crossArenaHandler.sendReqCrossArenaInfo()
            elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
                crossTeamArenaHandler.sendReqHighArenaInfo()
            else
                error("错误竞技场玩法类型")
                return
            end
        end
    end
end

    --打开段位预览界面
function UIArenaMain.onClickExplain() 
    local _arena_type = this.cur_arena_type 
    showUI(PanelNames.UIArenaLevelPreview, _arena_type)
end

function UIArenaMain.onClickRefresh()
    if refreshTimeNum <= 0 then
        if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
            logicMgr.ArenaManager.requestOpponentInfo(true)
            refreshTimeNum = tonumber(G.dataTable["t_global"]["71"]["f_int_value"]) / 1000
        elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
            logicMgr.ArenaManager.requestCrossOpponentInfo(true)
            refreshTimeNum = tonumber(G.dataTable["t_global"]["376"]["f_int_value"]) / 1000
        elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
            logicMgr.ArenaManager.requestCrossTeamOpponentInfo(true)
            refreshTimeNum = tonumber(G.dataTable["t_global"]["415"]["f_int_value"]) / 1000
        else
            error("错误竞技场玩法类型")
            return
        end

        
        if timeRefresh == nil then
            timeRefresh = Timer.New(function()
                refreshTimeNum = 0;
            end, refreshTimeNum, 1);
        else
            timeRefresh:Reset(function()
                refreshTimeNum = 0;
            end, refreshTimeNum, 1);
        end
        timeRefresh:Start();
    else
        UISysTips.AddMsg(string.format(getLanguage("Character_Tips11")));
    end
end

-- 设置防守阵容成功
function UIArenaMain.defFormationSaveSuccess()
    numDefendPowerText.text = this.getPower(EnumConst.FormationType.ArenaDef);
    closeUI(PanelNames.UIBattleTeam);
    --UISysTips.AddMsg(getLanguage("Character_Tips17"));

end
--设置防守阵容方法
function UIArenaMain.onClickFormation()
    local param = {}
    param.playerId = 0
    param.power = 0
    param.arena_type = this.cur_arena_type
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        param.type = EnumConst.FormationType.ArenaDef 
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        param.type = EnumConst.FormationType.CrossArenaDef
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        param.type = EnumConst.FormationType.TeamCrossArenaDef 
    else
        error("错误竞技场类型")
    end
    showUI(PanelNames.UIBattleTeam, EnumConst.FightTypeConst.ARENA, param, function(formations)
        typeCtrl.selectedPage = 0
        local flag = true
        if formations[1] ~= nil then
            for i = 1, #formations[1] do
                if formations[1][i] ~= nil and tonumber(tostring(formations[1][i])) > 0 then
                    flag = false
                    break
                end
            end
        end
        if flag then
            UISysTips.AddMsg("需要上阵至少一名英雄")
        else
            if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
                arenaHandler.sendDefFormation(formations[1])
            elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
                crossArenaHandler.sendCrossDefFormation(formations[1])
            elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
                if formations[2] ~= nil then
                    for i = 1, #formations[2] do
                        if formations[2][i] ~= nil and tonumber(tostring(formations[2][i])) > 0 then
                            flag = false
                            break
                        end
                    end
                end
                if flag then
                    if formations[3] ~= nil then
                        for i = 1, #formations[3] do
                            if formations[3][i] ~= nil and tonumber(tostring(formations[3][i])) > 0 then
                                flag = false
                                break
                            end
                        end
                    end
                end
                if flag then
                    UISysTips.AddMsg("每队至少上阵一名英雄")
                else
                    crossTeamArenaHandler.sendReqHighArenaSetDefFormation(formations)
                end
            else
                error("错误竞技场类型")
            end
        end
    end, function()
        --showCtrl.selectedPage = "show";
        typeCtrl.selectedPage = 0;
    end)
end

function UIArenaMain.onClickTickAdd()
    showUI(PanelNames.UIArenaTicketPurchase, this.cur_arena_type)
end

function UIArenaMain.onClickSource()
    this.showSourceController.selectedIndex = 1
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        this.showSourceList = {CurrencyEnum.ChallengeTicket}
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        this.showSourceList = {CurrencyEnum.CrossChallengeTicket}
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        this.showSourceList = {CurrencyEnum.CrossTeamChallengeTicket}
    else
        error("错误竞技场玩法类型")
        return
    end
    
    this.updateSource();
end

function UIArenaMain.updateSource()
    logicMgr.ItemManager.updateSourceUI(this.sourceUIobj, this.showSourceList, function ()
        this.showSourceController.selectedIndex = 0;
    end, function ()
        this.showSourceController.selectedIndex = 0;
        this.onClickClose();
        closeUI(PanelNames.UIArenaMainEnter);
        showUI(PanelNames.UIHeadMenu);
    end );
end

function UIArenaMain.onClickClose()
    closeUI(PanelNames.UIArenaMain);
    --if this.needShowHeadMenu then
    --    showUI(PanelNames.UIHeadMenu);
    --    this.needShowHeadMenu = nil;
    --end
end

function UIArenaMain.onClickRank()
    showUI(PanelNames.UIArenaRank, this.cur_arena_type) 
end

function UIArenaMain.onClickShop()
    showUI(PanelNames.UIShop, nil, nil, 4);    -- 4 野外界面
    --gameObject:SetActive(false);
    --showCtrl.selectedPage = "not";
end

function UIArenaMain.onClickWonderful()
    local _arena_type =  this.cur_arena_type
    showUI(PanelNames.UIArenaSpecialBattle, function()
        typeCtrl.selectedPage = 0;
    end, _arena_type)
end

function UIArenaMain.onClickRecord()
    local _arena_type = this.cur_arena_type
    showUI(PanelNames.UIArenaRecord, function()
        typeCtrl.selectedPage = 0;
    end, _arena_type);
end

function UIArenaMain.onClickReward()
    showUI(PanelResNames.UIReward)
    -- local _arena_type = this.cur_arena_type
    -- showUI(PanelNames.UIArenaWinReward, function()
    --     typeCtrl.selectedPage = 0;
    -- end, _arena_type);
end

function UIArenaMain.closeAllUI()
    closeUI(PanelNames.UIArenaMain);
    closeUI(PanelNames.UIAdventureMain);
    closeUI(PanelNames.UIBottom);
    closeUI(PanelResNames.UIHeadMenu);
end

function UIArenaMain.OnClickOpponentItem(opponent)
    local infoChallengeTicketNum = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.ChallengeTicket);
    local arenaBaseInfo = logicMgr.ArenaManager.getBaseInfo()
    if arenaBaseInfo.times < (arenaBaseInfo.freeTimes + logicMgr.EcoBuffManager.getEcoBuffByTypeAndItemId(Config.EcoBuffCondition.ArenaFreeTimes)) or infoChallengeTicketNum > 0 then
        local param = {};
        param.playerId = opponent.playerId;
        param.power = opponent.power;
        param.type = EnumConst.FormationType.ArenaAtk
        param.otherPetInfo = opponent.otherPetInfo
        param.arena_type = EnumConst.ArenaBattleType.Normal
        param.supSkillId = opponent.skillId;
        local isAI = opponent.isAI
        
        FightManager.SetRePlay(false)

        showUI(PanelNames.UIBattleTeam, EnumConst.FightTypeConst.ARENA, param, function(formations)
            timer:Reset(this.countDown, 1, 9999999)
            timer:Start()
            local flag = false;
            local form = formations[1];
            if form ~= nil then
                for k, v in pairs(form) do
                    if v ~= 0 then
                        flag = true
                        break
                    end
                end
            end
            if flag then
                logicMgr.FormationManager.SetFormation(EnumConst.FormationType.ArenaAtk, form);
                arenaHandler.sendArenaBattle(param.playerId, isAI, form)
                logicMgr.ArenaManager.resultDic.target_player_id = param.playerId
                logicMgr.ArenaManager.resultDic.is_robot = isAI
                logicMgr.ArenaManager.resultDic.hero_list = form
                local _arenaDic = {}
                _arenaDic.target_player_id = tostring(param.playerId)
                _arenaDic.is_robot = tostring(isAI)
                TAManager.TrackByDictionary("arena_battle_click_fight",_arenaDic)
            else
                UISysTips.AddMsg("请上阵英雄")
            end
        end, function()
        end);
    else
        showUI(PanelNames.UIArenaTicketPurchase, this.cur_arena_type);
        --UISysTips.AddMsg("道具不足，无法挑战");
        AudioManager.Play(2010)
    end
end

function UIArenaMain.showBuyPop()
    local needNum = 1
    --local needItemID = shopInfo["f_GoodsID"]
    local needItemName = getLanguage(G.dataTable["t_item"][tostring(CurrencyEnum.ChallengeTicket)])

    local needMoneyName = getLanguage("ItemName1");
    local needMoneyNum = decodeJsonStrToTabel(G.dataTable["t_global"]["73"])[2];
    local content1 = needMoneyNum .. needMoneyName--数量..货币名称
    local content2 = needItemName .. "x" .. needNum--道具名称..数量


    local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
    pop.Init("1", function(b)
        if b then
            local haveMoneyNum = logicMgr.ItemManager.getBagNumByTableID(1)
            if toNumber(haveMoneyNum) < toNumber(needMoneyNum) then
                UISysTips.AddMsg(needMoneyName .. "不足,无法购买");
                AudioManager.Play(2010)
            else
                logicMgr.arenaHandler.sendBuyTicket(1);
            end
        else
        end
    end, content1, content2);

end

function UIArenaMain.boxRewardGet(id)
    arenaHandler.sendDrawArenaBox(id);
end

function UIArenaMain.checkRewardId(id)
    local info = logicMgr.ArenaManager.getBaseInfo();
    for k, v in pairs(info["hasReward"]) do
        if id == v then
            return true;
        end
    end
    return false;
end
--根据tap获取防守阵容与进攻阵容的战力 EnumConst.FormationType枚举
function UIArenaMain.getPower(type)
    local power = 0;
    local formation = logicMgr.FormationManager.GetFormation(type);
    if formation ~= nil then
        for k, v in pairs(formation) do
            if v ~= nil and tostring(v) ~= "0" then
                if this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
                    power = power + logicMgr.HeroManager.CalcHeroPowerWithLv(tostring(v), 300);
                else
                    local data = logicMgr.HeroManager.getHeroDatabyPartnerId(tostring(v), true);
                    if data then
                        power = power + data.power;
                    end
                end
            end
        end
    end
    return HelperFunc.Format4ResourceNum(power);
end

function UIArenaMain.getPowers(type)
    local power = 0
    local formations = logicMgr.FormationManager.GetFormation(type)
    for _, formation in pairs(formations) do
        if formation ~= nil and formation ~= 0 and  formation ~= "0" then
            for k, v in pairs(formation) do
                if v ~= nil and tostring(v) ~= "0" then
                    if this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
                        power = power + logicMgr.HeroManager.CalcHeroPowerWithLv(tostring(v), 300);
                    else
                        local data = logicMgr.HeroManager.getHeroDatabyPartnerId(tostring(v), true);
                        if data then
                            power = power + data.power;
                        end
                    end
                end
            end
        end
    end
    return HelperFunc.Format4ResourceNum(power);
end


---------------------------------------------------------
-- 跨服竞技场
---------------------------------------------------------
-- 刷新跨服对手数据
function UIArenaMain.refreshCrossOpponent( opponent_list )
    this.opponent_data_list = opponent_list or {}
    this.opponent_list.numItems = #this.opponent_data_list
end
function UIArenaMain.renderOpponentListItem( index, obj)
    
    local player_icon_obj = obj:GetChild("PlayerIcon")
    local player_icon = player_icon_obj:GetChild("PlayerIcon")
    local txt_player_name = obj:GetChild("PlayerNameText")
    local txt_power_value = obj:GetChild("PowerText")
    -- local txt_score_label = obj:GetChild("textScore")
    local txt_score_value = obj:GetChild("ScoreText")
    local txt_server_name = obj:GetChild("textSevers")
    local btn_battle = obj:GetChild("BattleBtn")
    local ctrl_type = obj:GetController("type")
    local txt_level = obj:GetChild("level")
    local icon_level = obj:GetChild("LevelIcon")
    local img_level = obj:GetChild("Effect_Dwsg") 
    btn_battle.onClick:Clear()
 
    local item_info = this.opponent_data_list[index+1]
    if item_info ~= nil then 
        
        if this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
            ctrl_type:SetSelectedIndex(0)
            local cfg_grading = logicMgr.ArenaManager.getLevelConfigByScore(tonumber(tostring(item_info.score)), this.cur_arena_type)
            icon_level.url = EnumConst.AtlasPath.ICONAtlas .. cfg_grading.f_Icon
            local level_num = cfg_grading.f_Id
            img_level.animationName = "idle" .. level_num
            img_level.skinName = level_num
            img_level.loop = true
        elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
            ctrl_type:SetSelectedIndex(1)
            local cfg_grading, cfg_matching = ArenaManager.getAthleticGradingConfigByRank( tonumber(tostring(item_info.score)) )  
            icon_level.url = EnumConst.AtlasPath.ICONAtlas .. cfg_grading.f_Icon
            txt_level.text = getLanguage(cfg_matching.f_RankName) 
            local level_num = cfg_grading.f_RankId
            img_level.animationName = "idle" .. level_num
            img_level.skinName = level_num
            img_level.loop = true
        end

        txt_power_value.text = getNumString(tostring(item_info.power))
        txt_score_value.text = tostring(item_info.score)
        if AppConst.ServerId ~= item_info.server_id  then
            txt_player_name.text = string.format("[%s]%s", item_info.server_id, item_info.name)
        else
            txt_player_name.text = item_info.name or "--"
        end

        local sever_data = logicMgr.LoginManager.GetServerInAll(item_info.server_id)
        if sever_data ~= nil then
            txt_server_name.text = sever_data[Server_ENU_INDEX.NAME] 
        else
            txt_server_name.text = "未知"
        end

        -- player_icon.url = "ui://HalfBodyAtlas/hero_halfbody_" .. item_info.head
        player_icon.url = "ui://HalfBodyAtlas/" .. logicMgr.SkinManager.GetHeroBIconBySkinId(item_info.head, item_info.head)

        btn_battle.onClick:Add(function() 
            if this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
                this.OnClickCrossOpponentItem(item_info)
            elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
                this.OnClickCrossTeamOpponentItem(item_info)
            end
        end)
    else
        txt_player_name.text = "--"
        txt_power_value.text = "0"
        -- txt_score_value.text = "0"
        txt_server_name.text = "--"
        player_icon.url = "ui://HalfBodyAtlas/hero_halfbody_9"
    end
    
end
-- 点击跨服对战
function UIArenaMain.OnClickCrossOpponentItem(opponent) 
    local infoChallengeTicketNum = logicMgr.ItemManager.getItemCountbyItemTypeAndItemModelId(EnumConst.ItemTableEnum.Item, CurrencyEnum.CrossChallengeTicket) or 0  
    local arenaCrossBaseInfo = logicMgr.ArenaManager.getCrossBaseInfo()
    if (arenaCrossBaseInfo.times < arenaCrossBaseInfo.freeTimes) or infoChallengeTicketNum > 0 then
        local param = {};
        param.playerId = opponent.playerId
        param.power = opponent.power
        param.type = EnumConst.FormationType.CrossArenaAtk
        param.otherPetInfo = opponent.otherPetInfo
        param.arena_type = EnumConst.ArenaBattleType.Cross -- 竞技场类型
        param.supSkillId = opponent.skillId;
        local isAI = opponent.isAI
        local target_server_id = opponent.server_id 
        FightManager.SetRePlay(false) 
        showUI(PanelNames.UIBattleTeam, EnumConst.FightTypeConst.ARENA, param, function(formations) 
            timer:Reset(this.countDown, 1, 9999999)
            timer:Start()
            local flag = false;
            local form = formations[1]
            if form ~= nil then
                for k, v in pairs(form) do
                    if v ~= 0 then
                        flag = true
                        break
                    end
                end
            end
            if flag then
                logicMgr.FormationManager.SetFormation(EnumConst.FormationType.CrossArenaAtk, form) 
                crossArenaHandler.sendCrossArenaBattle(param.playerId, isAI, form)

                logicMgr.ArenaManager.resultDicCross.target_player_id = param.playerId
                logicMgr.ArenaManager.resultDicCross.is_robot = isAI
                -- logicMgr.ArenaManager.resultDicCross.hero_list = form
                logicMgr.ArenaManager.resultDicCrossTeam.target_server_id = target_server_id
                local _arenaDic = {}
                _arenaDic.target_player_id = tostring(param.playerId)
                _arenaDic.is_robot = tostring(isAI)
                _arenaDic.target_server_id = tostring(target_server_id)
                TAManager.TrackByDictionary("cross_arena_battle_click_fight",_arenaDic)
            else
                UISysTips.AddMsg("请上阵英雄")
            end
        end, function() 
        end)
    else
        showUI(PanelNames.UIArenaTicketPurchase, this.cur_arena_type)
        AudioManager.Play(2010)
    end
end

-- 刷新跨服
function UIArenaMain.refreshCross()
    local rewardCfg = G.dataTable["t_arenaboxrewardcs"]
    local baseInfo = logicMgr.ArenaManager.getCrossBaseInfo()
    if baseInfo == nil then return end
    if baseInfo.add == nil then baseInfo.add = 0 end

    local gradingCfg, newLevel = ArenaManager.getLevelConfigByScore( baseInfo.score, EnumConst.ArenaBattleType.Cross)
    local baseInfo = ArenaManager.getCrossBaseInfo()
    if baseInfo.isLevelUp == 1 then
        baseInfo.isLevelUp = 0 
        levelUpController.selectedIndex = 1--播放等级修改动画
        upAni.skinName = newLevel
        local upAniState = upAni.spineAnimation.state
        upAniState:SetAnimation(0, "idle1", false)
        local idleAniTime = upAniState.Data.SkeletonData:FindAnimation("idle1").Duration
        if idleTimer == nil then
            idleTimer = Timer.New(this.delayIdle, idleAniTime, 1, false);
        else
            idleTimer:Reset(this.delayIdle, idleAniTime, 1, false);
        end
        idleTimer:Start();
        levelUpPage:GetChild("n12").onClick:Add(function()
            if idleTimer ~= nil then
                idleTimer:Stop();
            end
            levelUpController.selectedIndex = 0;
            levelUpPage.onClick:Clear()
        end)
    end

    textRankText.text = getLanguage(gradingCfg.f_Name) -- 排名积分段位
    imgLevel.animationName = "idle" .. newLevel        -- 段位等级特效
    imgLevel.skinName = newLevel
    imgLevel.loop = true
 
    numMyRankText.text = baseInfo["rank"] > 0 and string.format(getLanguage("ArenaTips4"), baseInfo["rank"]) or getLanguage("NotInRank") -- 我的排名
    numMyPointText.text = baseInfo["score"]     -- 我的积分
    numDefendPowerText.text = this.getPower(EnumConst.FormationType.CrossArenaDef) -- 我的防守战力
    numHighPowerText.text = this.getPower(EnumConst.FormationType.CrossArenaAtk)    -- 我的攻击战力

    local maxKillCount = rewardCfg["5"].f_winCount 
    numRewardBarText.text = baseInfo["winCount"] .. "/" .. maxKillCount         -- 奖励进度
    rewardProgressBar.value = (baseInfo["winCount"] / maxKillCount) * 100       -- 奖励进度条
 
    this.refreshCrossTicket()
    local lastNum = baseInfo.freeTimes - baseInfo.times
    if lastNum > 0 then
        arenaTips.text = string.format(getLanguage("ArenaTips1"), lastNum);
    else
        arenaTips.text = getLanguage("ArenaTips2")
    end

    this.countDown();
    timer:Stop();
    timer:Reset(this.countDown, 1, -1);
    timer:Start();

    this.refreshCrossOpponent(logicMgr.ArenaManager.getCrossOpponentInfo())
end

-- 更新跨服挑战券信息
function UIArenaMain.refreshCrossTicket()
    -- local tickNum = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.CrossChallengeTicket)
    local tickNum = logicMgr.ItemManager.getItemCountbyItemTypeAndItemModelId(EnumConst.ItemTableEnum.Item, CurrencyEnum.CrossChallengeTicket) or 0  
    local singleItemConfig = logicMgr.ItemManager.getItemConstDatabyModelId(CurrencyEnum.CrossChallengeTicket)
    imgTickIcon.url = "ui://ItemAtlas/" .. singleItemConfig["icon"]
    txtTickCount.text = tostring(tickNum)
end
-- 检查是否领取跨服奖励
function UIArenaMain.checkCrossRewardId(id)
    local info = logicMgr.ArenaManager.getCrossBaseInfo()
    for k, v in pairs(info["hasReward"]) do
        if id == v then
            return true;
        end
    end
    return false;
end
-- 领取跨服奖励
-- function UIArenaMain.boxCrossRewardGet(id)
--     crossArenaHandler.sendCrossDrawArenaBox(id)
-- end
-- 设置跨服防守阵容成功
function UIArenaMain.defFormationCrossSaveSuccess()
    numDefendPowerText.text = this.getPower(EnumConst.FormationType.CrossArenaDef)
    closeUI(PanelNames.UIBattleTeam)
    --UISysTips.AddMsg(getLanguage("Character_Tips17"))
end
 
---------------------------------------------------------
-- end
---------------------------------------------------------


---------------------------------------------------------
-- 跨服组队竞技场
---------------------------------------------------------
-- 刷新金币数据
function UIArenaMain.refreshCrossTeamArenaAward()
    local baseInfo = logicMgr.ArenaManager.getCrossTeamBaseInfo() 
    if baseInfo == nil then return end
    
    local _, cfg_arena_matching_item = ArenaManager.getAthleticGradingConfigByRank(baseInfo.rank)
    this.txt_produce.text = string.format("%s/小时", cfg_arena_matching_item.f_Coin)
    this.txt_storage.text = string.format("%s/%s", baseInfo.award, cfg_arena_matching_item.f_CoinLimit)
    this.img_icon.url = EnumConst.AtlasPath.ItemAtlas..logicMgr.ItemManager.GetItemIcon(31)

    if this.box_effect_ani ~= nil then
        utimer.delayCall(function()
            local rate = baseInfo.award/cfg_arena_matching_item.f_CoinLimit
            if rate >= 0.5 then
                Util.PlayAction(this.box_effect_ani, "idle2", true)
            else
                Util.PlayAction(this.box_effect_ani, "idle", true)
            end 
        end, 1000 )
    end
    
end
-- 刷新跨服组队
function UIArenaMain.refreshCrossTeam() 
    local baseInfo = logicMgr.ArenaManager.getCrossTeamBaseInfo()
    if baseInfo == nil then return end
    if baseInfo.add == nil then baseInfo.add = 0 end
 
    if this.ctrl_box_state ~= nil then
        if baseInfo.rank >= 131 then
            this.ctrl_box_state:SetSelectedIndex(1)
        else
            this.ctrl_box_state:SetSelectedIndex(0)
        end
    end

    local gradingCfg, cfg_arena_matching_item = ArenaManager.getAthleticGradingConfigByRank(baseInfo.rank)
     
    this.txt_produce.text = string.format("%s/小时", cfg_arena_matching_item.f_Coin)
    this.txt_storage.text = string.format("%s/%s", baseInfo.award, cfg_arena_matching_item.f_CoinLimit)
    if this.box_effect_ani ~= nil then
        local rate = baseInfo.award/cfg_arena_matching_item.f_CoinLimit
        if rate >= 0.5 then
            Util.PlayAction(this.box_effect_ani, "idle2", true)
        else
            Util.PlayAction(this.box_effect_ani, "idle", true)
        end 
    end
    this.img_icon.url = EnumConst.AtlasPath.ItemAtlas..logicMgr.ItemManager.GetItemIcon(31)
    numMyRankText.text = getLanguage(cfg_arena_matching_item.f_RankName)
    --baseInfo["rank"] > 0 and string.format(getLanguage("ArenaTips4"), baseInfo["rank"]) or getLanguage("NotInRank") -- 我的排名

    if baseInfo.isLevelUp == 1 then
        local newLevel = cfg_arena_matching_item.f_RankId
        baseInfo.isLevelUp = 0 
        levelUpController.selectedIndex = 1--播放等级修改动画
        upAni.skinName = newLevel  
        local upAniState = upAni.spineAnimation.state
        upAniState:SetAnimation(0, "idle1", false)
        local idleAniTime = upAniState.Data.SkeletonData:FindAnimation("idle1").Duration
        if idleTimer == nil then
            idleTimer = Timer.New(this.delayIdle, idleAniTime, 1, false)
        else
            idleTimer:Reset(this.delayIdle, idleAniTime, 1, false)
        end
        idleTimer:Start();
        levelUpPage:GetChild("n12").onClick:Add(function()
            if idleTimer ~= nil then
                idleTimer:Stop();
            end
            levelUpController.selectedIndex = 0;
            levelUpPage.onClick:Clear()
        end)
    end
    local newLevel = gradingCfg.f_RankId
    textRankText.text = getLanguage(gradingCfg.f_Name) -- 排名积分段位
    imgLevel.animationName = "idle" .. newLevel        -- 段位等级特效
    imgLevel.skinName = newLevel
    imgLevel.loop = true
    numMyPointText.text = baseInfo["score"]     -- 我的积分
    numDefendPowerText.text = this.getPowers(EnumConst.FormationType.TeamCrossArenaDef) -- 我的防守战力
    numHighPowerText.text = this.getPowers(EnumConst.FormationType.TeamCrossArenaAtk)    -- 我的攻击战力 
    this.refreshCrossTeamTicket()
    local lastNum = baseInfo.freeTimes - baseInfo.times
    if lastNum > 0 then
        arenaTips.text = string.format(getLanguage("ArenaTips1"), lastNum);
    else
        arenaTips.text = getLanguage("ArenaTips2")
    end
    if baseInfo.rank ~= nil and baseInfo.rank == 1 then
        this.teamCrossFirstCtrl.selectedIndex = 1;
    else
        this.teamCrossFirstCtrl.selectedIndex = 0;
    end
    this.countDown()
    timer:Stop()
    timer:Reset(this.countDown, 1, -1)
    timer:Start()
    this.refreshCrossTeamOpponent(logicMgr.ArenaManager.getCrossTeamOpponentInfo())
end
 
-- 设置跨服组队防守阵容成功
function UIArenaMain.defFormationCrossTeamSaveSuccess()
    numDefendPowerText.text = this.getPowers(EnumConst.FormationType.TeamCrossArenaDef)
    closeUI(PanelNames.UIBattleTeam)
end

-- 更新跨服组队挑战券信息
function UIArenaMain.refreshCrossTeamTicket()
    local tickNum = logicMgr.ItemManager.getItemCountbyItemTypeAndItemModelId(EnumConst.ItemTableEnum.Item, CurrencyEnum.CrossTeamChallengeTicket) or 0  
    local singleItemConfig = logicMgr.ItemManager.getItemConstDatabyModelId(CurrencyEnum.CrossTeamChallengeTicket)
    imgTickIcon.url = "ui://ItemAtlas/" .. singleItemConfig["icon"]
    txtTickCount.text = tostring(tickNum)
end

-- 点击跨服组队对战
function UIArenaMain.OnClickCrossTeamOpponentItem(opponent) 
    -- print("UIArenaMain.OnClickCrossTeamOpponentItem-->", table.tostring(opponent) )
    local infoChallengeTicketNum = logicMgr.ItemManager.getItemCountbyItemTypeAndItemModelId(EnumConst.ItemTableEnum.Item, CurrencyEnum.CrossTeamChallengeTicket) or 0  
    local arenaCrossBaseInfo = logicMgr.ArenaManager.getCrossTeamBaseInfo()
    if (arenaCrossBaseInfo.times < arenaCrossBaseInfo.freeTimes) or infoChallengeTicketNum > 0 then
        local param = {}
        param.playerId = opponent.playerId
        param.power = opponent.power
        param.type = EnumConst.FormationType.TeamCrossArenaAtk
        param.otherPetInfo = opponent.otherPetInfo
        param.arena_type = EnumConst.ArenaBattleType.TeamCross -- 多队跨服竞技场类型
        param.supSkillId = opponent.skillId;
        param.name = opponent.name
        param.pic = opponent.head
        local isAI = opponent.isAI
        local target_server_id = opponent.server_id
        local target_score = opponent.score
        local my_score = tonumber(tostring(arenaCrossBaseInfo.score))
        FightManager.SetRePlay(false) 
        showUI(PanelNames.UIBattleTeam, EnumConst.FightTypeConst.ARENA, param, function(formations) 
            timer:Reset(this.countDown, 1, 9999999)
            timer:Start()
            local flag1 = false
            if formations[1] ~= nil then
                for _, v in pairs(formations[1]) do
                    if v ~= 0 then
                        flag1 = true
                        break
                    end
                end
            end
            local flag2 = false
            if formations[2] ~= nil then
                for _, v in pairs(formations[2]) do
                    if v ~= 0 then
                        flag2 = true
                        break
                    end
                end
            end 
            local flag3 = false
            if formations[3] ~= nil then
                for _, v in pairs(formations[3]) do
                    if v ~= 0 then
                        flag3 = true
                        break
                    end
                end
            end 
            if flag1 and flag2 and flag3 then 
                logicMgr.FormationManager.SetFormation(EnumConst.FormationType.TeamCrossArenaAtk, formations)
                FightManager.arena_team_defener_score  = tonumber(tostring(opponent.score))
                FightManager.arena_team_attacker_score = my_score
                crossTeamArenaHandler.sendReqHighArenaBattle(param.playerId, isAI, formations) 

                logicMgr.ArenaManager.resultDicCrossTeam.target_player_id = param.playerId
                logicMgr.ArenaManager.resultDicCrossTeam.is_robot = isAI
                logicMgr.ArenaManager.resultDicCrossTeam.target_server_id = tostring(target_server_id)
                logicMgr.ArenaManager.resultDicCrossTeam.target_level_id = tostring(target_score)
                local cross_team_info = ArenaManager.getCrossTeamBaseInfo()
                logicMgr.ArenaManager.resultDicCrossTeam.my_level_id = cross_team_info.score
                -- logicMgr.ArenaManager.resultDicCrossTeam.hero_list = formations

                -- local _arenaDic = {}
                -- _arenaDic.target_player_id = tostring(param.playerId)
                -- _arenaDic.is_robot = tostring(isAI)
                -- _arenaDic.target_server_id = tostring(target_server_id)
                -- _arenaDic.my_level_id = tostring(logicMgr.ArenaManager.resultDicCrossTeam.my_level_id)
                -- _arenaDic.target_level_id = tostring(target_score)
                -- TAManager.TrackByDictionary("cross_team_arena_battle_click_fight",_arenaDic)
            else
                UISysTips.AddMsg("每队至少上阵一名英雄") 
            end
        end, function() 
        end)
    else
        showUI(PanelNames.UIArenaTicketPurchase, this.cur_arena_type)
        AudioManager.Play(2010)
    end
end

function UIArenaMain.refreshCrossTeamOpponent( opponent_list )
    this.opponent_data_list = opponent_list or {}
    this.opponent_list2.numItems = #this.opponent_data_list
end

---------------------------------------------------------
-- end
---------------------------------------------------------

return UIArenaMain;
